package com.ityy.ruiji.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ityy.ruiji.common.R;
import com.ityy.ruiji.dao.CategoryDao;
import com.ityy.ruiji.dao.DishDao;
import com.ityy.ruiji.dao.SetmealDao;
import com.ityy.ruiji.entity.Category;
import com.ityy.ruiji.entity.Page;
import com.ityy.ruiji.exception.CustomerException;
import com.ityy.ruiji.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired(required = false)
    CategoryDao categoryDao;

    @Autowired(required = false)
    DishDao dishDao;

    @Autowired(required = false)
    SetmealDao setmealDao;

    @Override
    public R<Page> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Category> categoryList = categoryDao.findAll();
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> page1 = new Page<>(pageInfo.getList(),pageInfo.getTotal());
        return R.success(page1);
    }

    @Override
    public R save(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        int row = categoryDao.save(category);
        if (row>0){
            return R.success("新增菜品成功");
        }
        else {
            return R.error("新增菜品失败");
        }
    }

    @Override
    public R deleteById(Long id) {
        Long countByCategoryId = dishDao.findCountByCategoryId(id);
        Long countByCategoryId1 = setmealDao.findCountByCategoryId(id);
        if (countByCategoryId>0 || countByCategoryId1>0){
            throw new CustomerException("这个类别已经关联其他菜品，不能够直接删除");
        }
        int row =  categoryDao.deleteById(id);
       if (row>0){
           return R.success("删除成功");
       }
       else {
           return R.error("删除失败");
       }
    }

    @Override
    public R updateById(Category category) {
        //1. 设置修改的时间
        category.setUpdateTime(LocalDateTime.now());
       int row= categoryDao.updateById(category);
        if (row>0){
            return R.success("修改成功");
        }
        else {
            return R.error("修改失败");
        }
    }

    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }

    @Override
    public R list(Integer type) {
        List<Category> categoryList = categoryDao.list(type);
        return R.success(categoryList);
    }
}
